package com.code2roc.jarmanage.firewall;

import com.code2roc.jarmanage.util.CMDUtil;
import com.code2roc.jarmanage.util.StringUtil;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LinuxFireWallService implements FireWallService {

    @Override
    public boolean addRule(String name, String protocol, String port, String action) {
        protocol = protocol.toLowerCase();
        String command = MessageFormat.format("firewall-cmd --permanent --add-port={0}{1}{2}", port, "/", protocol);
        CMDUtil.executeLinuxCommand(command);
        command = "firewall-cmd --reload";
        CMDUtil.executeLinuxCommand(command);
        List<String> ruleList = getRuleList();
        if(ruleList.contains(port + "/" + protocol)){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean deleteRule(String name, String protocol, String port, String action) {
        protocol = protocol.toLowerCase();
        String command = MessageFormat.format("firewall-cmd --permanent --remove-port={0}{1}{2}", port, "/", protocol);
        CMDUtil.executeLinuxCommand(command);
        command = "firewall-cmd --reload";
        CMDUtil.executeLinuxCommand(command);
        List<String> ruleList = getRuleList();
        if(!ruleList.contains(port + "/" + protocol)){
            return true;
        }else{
            return false;
        }
    }

    private List<String> getRuleList(){
        List<String> ruleList = new ArrayList<>();
        String command = "firewall-cmd --list-ports";
        String result = CMDUtil.executeLinuxCommand(command);
        if(!StringUtil.isEmpty(result)){
            ruleList = Arrays.asList(result.split(" "));
        }
        return ruleList;
    }
}
